package com.cms.service;

import com.cms.mapper.AdminMapper;
import com.cms.pojo.Admin;
import com.cms.pojo.Student;
import com.cms.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class AdminService {
    // 获取SqlSessionFactory对象
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /***
     * 登录
     * @param username
     * @param password
     * @param role
     * @return
     */
    public Admin login(String username, String password, int role) {
        // 获取SqlSession
        SqlSession sqlSession = factory.openSession();

        // 获取AdminMapper
        AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);

        // 调用方法
        Admin admin;
        if (role == 1) {
            admin = mapper.selectS(username, password);
        } else if (role == 2) {
            admin = mapper.selectT(username, password);
        } else {
            admin = mapper.selectA(username, password);
        }

        sqlSession.close();

        return admin;
    }

    /***
     * 注册
     * @param admin
     * @param role
     * @return
     */
    public boolean Register(Admin admin, int role) {
        // 获取SqlSession
        SqlSession sqlSession = factory.openSession();

        // 获取UserMapper
        AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);

        // 判断用户名是否存在
        Admin user;
        if (role == 1) {
            user = mapper.selectByUsernameS(admin.getUsername());
            if (user == null) {
                // 用户名不存在，注册
                mapper.addS(admin);
                sqlSession.commit();
            }
        } else {
            user = mapper.selectByUsernameT(admin.getUsername());
            if (user == null) {
                // 用户名不存在，注册
                mapper.addT(admin);
                sqlSession.commit();
            }
        }

        return user == null;
    }

    public List<Student> courseStudent(int id) {
        // 获取SqlSession
        SqlSession sqlSession = factory.openSession();

        // 获取UserMapper
        AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);

        List<Student> students = mapper.courseStudent(id);

        sqlSession.close();

        return students;
    }
}
